using System.Text;
using LostOrFind.Context;
using LostOrFind.Models;
using LostOrFind.Repositories;
using LostOrFind.Repositories.Impl;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(corsPolicyBuilder =>
    {
        corsPolicyBuilder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
var serverVersion = new MySqlServerVersion(new Version(8, 0, 34));

// Replace 'YourDbContext' with the name of your own DbContext derived class.
builder.Services.AddDbContext<MyDbContext>(
    dbContextOptions =>
    {
        dbContextOptions
            .UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), serverVersion)
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors();
    }
);
builder.Services.AddScoped<IOccasionRepository, OccasionRepository>();
builder.Services.AddCors();
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("Jwt"));
var jswSettings = builder.Configuration.GetSection("Jwt").Get<JwtSettings>();
var secretKey = Encoding.UTF8.GetBytes(jswSettings!.SecretKey!);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = jswSettings.Issuer,
            ValidAudience = jswSettings.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(secretKey)
        };
    });

builder.Services.AddAuthorization();
var app = builder.Build();
app.UseCors();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();